from rest_framework import mixins, status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from drf_yasg.utils import swagger_auto_schema

from api.auth import JWTAuthentication
from api.models.order import Order
from api.routes.order.serializer import (
    OrderQeurySerializer,
    OrderBodySerializer,
    OrderDataSerializer,
    OrderIdSerializer,
    OrderUpdateAddressSerializer,
)
from api.utils.common import with_common_response, paginate_list


class OrderViewSet(viewsets.ViewSet):
    permission_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="订单列表",
        operation_description="订单列表",
        query_serializer=OrderQeurySerializer,
        responses=with_common_response({status.HTTP_200_OK: OrderDataSerializer}),
    )
    def list(self, request):
        serializer = OrderQeurySerializer(data=request.GET)
        if serializer.is_valid(raise_exception=True):
            product = serializer.validated_data.get("product")
            title = serializer.validated_data.get("title")
            per_page = serializer.validated_data.get("per_page")
            page = serializer.validated_data.get("page")
            limit = serializer.validated_data.get("limit")
            username = serializer.validated_data.get("username")
            order_status = serializer.validated_data.get("status")

            query_filter = {"cancel": False}
            if product:
                query_filter.update({"order_lines__prodcut": product})
            if title:
                query_filter.update({"order_lines__title": title})
            if order_status:
                query_filter.update({"status": order_status})
            if username:
                query_filter.update({"user__username": username})

            orders = Order.objects.filter(**query_filter)

            data, total = paginate_list(orders, page, per_page, limit)

            response = OrderDataSerializer({"total": total, "data": data})

            return Response(status=status.HTTP_200_OK, data=response.data)

    @swagger_auto_schema(
        operation_summary="订单详情",
        operation_description="订单详情",
        responses=with_common_response({status.HTTP_200_OK: OrderBodySerializer}),
    )
    def retrieve(self, request, pk):
        try:
            order = Order.objects.get(id=pk)
        except Order.DoesNotExist as e:
            raise e
        response = OrderBodySerializer(order)

        return Response(status=status.HTTP_200_OK, data=response.data)

    @swagger_auto_schema(
        operation_summary="取消订单",
        operation_description="取消订单",
        responses=with_common_response({status.HTTP_204_NO_CONTENT: OrderIdSerializer}),
    )
    def destroy(self, request, pk):
        try:
            order = Order.objects.get(id=pk)
        except Order.DoesNotExist as e:
            raise e
        order.cancel = True
        order.save()
        response = OrderIdSerializer(order)

        return Response(status=status.HTTP_204_NO_CONTENT, data=response.data)

    @swagger_auto_schema(
        operation_summary="订单更新（对收货地址的更新）",
        operation_description="订单更新（对收货地址的更新）",
        request_body=OrderUpdateAddressSerializer,
        responses=with_common_response({status.HTTP_202_ACCEPTED: OrderIdSerializer}),
    )
    def update(self, request, pk):
        try:
            order = Order.objects.get(id=pk)
        except Order.DoesNotExist as e:
            raise e

        serizlizer = OrderUpdateAddressSerializer(data=request.data)
        if serizlizer.is_valid(raise_exception=True):
            province = serizlizer.validated_data.get("province")
            city = serizlizer.validated_data.get("city")
            area = serizlizer.validated_data.get("area")
            detailed = serizlizer.validated_data.get("detailed")

            update_body = {}
            if province:
                update_body.update({"province": province})
            if city:
                update_body.update({"city": city})
            if area:
                update_body.update({"area": area})
            if detailed:
                update_body.update({"detailed": detailed})

            order.address.objects.update(**update_body)

            order.address.save()

            response = OrderIdSerializer(order)
            return Response(status=status.HTTP_202_ACCEPTED, data=response.data)
